package com.company.app.services;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import com.luciad.imageio.webp.WebPReadParam;
import com.company.app.constants.FileExtension;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.io.FileNotFoundException;

public class WebpHandler {
  public JLabel showWebpImage(JLabel imageLabel, String imagePath) {
    // 通过SwingWorker将图片加载和显示的逻辑放在单独的线程中来改善性能
    SwingWorker<BufferedImage, Void> worker = new SwingWorker<BufferedImage, Void>() {
      @Override
      protected BufferedImage doInBackground() throws Exception {// 先执行
        System.out.println(this + ".showWebpImage.doInBackground.ThreadID=" +
            Thread.currentThread().getId());
        return obtainWebpBufImg(imagePath);
      }

      @Override
      protected void done() {// 再执行
        try {
          BufferedImage bufImg = get();
          if (bufImg != null) {
            System.out.println("bufImg.getWidth=" + bufImg.getWidth());
            System.out.println("bufImg.getHeight=" + bufImg.getHeight());

            OpenPhotoHandler op = new OpenPhotoHandler();
            // 缩放旋转后的图片,并设置平滑缩放模式
            Image scaledImage = op.scaleImage(imageLabel, bufImg);
            // 将缩放后的图片设置为 imageLabel 的图标
            imageLabel.setIcon(new ImageIcon(scaledImage));
          } else {
            System.out.println(this + " BufImg Is NULL...");
          }
          System.out.println(this + ".showWebpImage.done.ThreadID=" +
              Thread.currentThread().getId());
        } catch (Exception ex) {
          System.out.println(this + " Error loading image:" + ex.getMessage());
        }
      }
    };

    worker.execute();
    return imageLabel;
  }

  public BufferedImage obtainWebpBufImg(String inputWebpPath) {
    BufferedImage buffImg = null;
    // 创建WebP ImageReader实例
    ImageReader reader = ImageIO.getImageReadersByMIMEType(FileExtension.TYPE_WEBP).next();
    // 配置解码参数
    WebPReadParam readParam = new WebPReadParam();
    readParam.setBypassFiltering(true);
    // 在ImageReader设置读取的原文件
    try {
      reader.setInput(new FileImageInputStream(new File(inputWebpPath)));
      // 解码图像
      buffImg = reader.read(0, readParam);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return buffImg;
  }
}